<template>
  <el-dialog
    class="add_dialog"
    width="600px"
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-width="100px"
    >
      <el-form-item
        label="分类名称:"
        prop="name"
      >
        <el-input
          v-model="form.name"
          maxlength="5"
          :show-word-limit="true"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="标语:"
        prop="title"
      >
        <el-input
          v-model="form.title"
          maxlength="4"
          :show-word-limit="true"
          placeholder="请输入推广副标题"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="状态:"
        prop="status"
      >
        <el-radio v-model="form.status" :label="1">显示</el-radio>
        <el-radio v-model="form.status" :label="2">隐藏</el-radio>
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        size="small"
        @click="dialogVisible = false"
      >取 消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="submit"
      >保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addOrEditH5PromotionCate } from "@/api/recommend";
export default {
  props: ["editItem"],
  data() {
    return {
      dialogVisible: false,
      form: {
        name: "",
        title: "",
        status: 2
      },
      rules: {
        name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '标语不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.editItem ? "编辑推广分类" : "添加推广分类";
    }
  },
  methods: {
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addOrEditH5PromotionCate(this.form).then(res => {
            this.dialogVisible = false;
            this.$emit("getList");
          })
        } else {
          this.$message({
            message: "请检查表单错误",
            type: "error"
          });
          return false;
        }
      });
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs['form'].resetFields();
          if (this.editItem) {
            // 编辑
            this.form.id = this.editItem.id;
            this.form.name = this.editItem.name;
            this.form.title = this.editItem.title;
            this.form.status = this.editItem.status;
          }
        });
      } else {
        this.form = {
          name: "",
          title: "",
          status: 2
        };
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
